import { Button, Space, Form, message, Spin } from 'antd';
import React, { useState } from 'react';
import AvatarDropdown from './AvatarDropdown';
import styles from './index.less';
import { WalletOutlined } from '@ant-design/icons';
import { getAccount, postAccount } from '@/services/aqchain-antd/account';
import { useModel } from '@@/plugin-model/useModel';
import { history } from '@@/core/history';
import RegisterModalForm from '@/components/RightContent/RegisterModalForm';

const RightContent: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');

  if (!initialState) {
    return <Spin />;
  }

  const { provider, currentAccount } = initialState;

  const [modalVisit, setModalVisit] = useState(false);

  /** 此方法会跳转到 redirect 参数所在的位置 */
  const goto = () => {
    if (!history) return;
    setTimeout(() => {
      const { query } = history.location;
      const { redirect } = query as { redirect: string };
      history.push(redirect || '/welcome');
    }, 10);
  };

  const connect = async () => {
    if (provider === undefined) {
      // todo 处理未安装钱包流程
      console.error('钱包初始化失败');
      return;
    }
    // 发送账户请求触发连接
    const ethereum = window.ethereum as any;
    const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
    const address = accounts[0];
    try {
      // 获取钱包账户信息
      const response = await getAccount({ address });
      const currentAccount = response.data;
      if (response.success) {
        const currentAccount = response.data;
        // 已存在账户信息完成连接
        setInitialState({ ...initialState, currentAccount });
        goto();
        return;
      } else {
        message.error(response.errorMessage);
        // 不存在账户信息时进行注册
        setModalVisit(true);
      }
    } catch (e) {
      console.error(e.message);
    }
  };

  return (
    <div>
      <Space size="large" className={`${styles.right}  ${styles.dark}`}>
        {!currentAccount && (
          <Button icon={<WalletOutlined />} onClick={connect}>
            关联钱包
          </Button>
        )}
        <AvatarDropdown />
        <RegisterModalForm
          modalVisit={modalVisit}
          setModalVisit={setModalVisit}
        />
      </Space>
    </div>
  );
};

export default RightContent;
